from django.db import models
from user.models import UserProfile

# Create your models here.


class ModelType(models.Model):
    type = models.CharField(max_length=30, verbose_name='模型名称')

    class Meta:
        db_table = 'ModelType'
        verbose_name = '模型管理'
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.type


class ApiKey(models.Model):
    key = models.CharField(max_length=51, verbose_name='API Key')
    model = models.ForeignKey(ModelType, on_delete=models.CASCADE, verbose_name='模型')
    hostname = models.CharField(max_length=100, verbose_name='中转链接', help_text='不填则默认为 https://api.openai.com/v1')
    state = models.BooleanField(default=True, verbose_name='状态')
    creatTime = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')

    class Meta:
        db_table = 'ApiKey'
        verbose_name = 'Key池管理'
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.key


class AllowModel(models.Model):
    type = models.ForeignKey(ModelType, on_delete=models.CASCADE, verbose_name='模型')
    defaultCount = models.IntegerField(default=0, verbose_name='默认次数', help_text='创建时所有用户的默认使用次数')
    OrdinaryMemberCount = models.IntegerField(default=0, verbose_name='体验用户默认使用次数', help_text='每日重置时体验用户的使用次数')
    PremiumMemberCount = models.IntegerField(default=0, verbose_name='高级用户默认使用次数', help_text='每日重置时普通用户的使用次数')
    AnnualMemberCount = models.IntegerField(default=0, verbose_name='年费用户默认使用次数', help_text='每日重置时年费用户的次数')

    def save(self, *args, **kwargs):
        if not self.pk:  # pk属性为None则为新建函数
            for item in UserProfile.objects.all():
                item.count.setdefault(self.type.type, self.defaultCount)
                item.save()
        else:
            old = AllowModel.objects.get(pk=self.pk)
            old_field_value = old.type.type
            for item in UserProfile.objects.all():
                item.count[self.type.type] = item.count[old_field_value]
                item.count.pop(old_field_value)
                item.save()
        super().save(*args, **kwargs)

    class Meta:
        db_table = 'AllowModel'
        verbose_name = '可用模型管理'
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.type.type